# users/views.py
from rest_framework.response import Response
from .serializers import RegisterSerializer, LoginSerializer, EmailVerificationSerializer, AvatarSerializer, DailyActivitySerializer
from .models import User, EmailVerification, Avatar, DailyActivity
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.conf import settings
from django.utils import timezone
import random
import string
from rest_framework.permissions import AllowAny
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework import generics, status

from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated

def generate_verification_code(length=6):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

class RegisterView(generics.CreateAPIView):
    serializer_class = RegisterSerializer
    permission_classes = [AllowAny]

    def post(self, request, *args, **kwargs):
        """
        用户注册
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        return Response({"detail": "注册成功。"}, status=status.HTTP_201_CREATED)

class LoginView(generics.GenericAPIView):
    serializer_class = LoginSerializer
    permission_classes = [AllowAny]

    def post(self, request, *args, **kwargs):
        """
        用户登录
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']

        # 更新用户的最后登录日期和连续登录天数
        today = timezone.now().date()
        profile = user.profile

        if profile.last_login_date == today - timezone.timedelta(days=1):
            profile.consecutive_login_days += 1
        elif profile.last_login_date != today:
            profile.consecutive_login_days = 1

        profile.last_login_date = today
        profile.daily_check_in += 1
        profile.save()

        # 创建或更新 DailyActivity
        daily_activity, created = DailyActivity.objects.get_or_create(user=user, date=today)
        daily_activity.is_logged_in = True
        daily_activity.save()

        # 生成 JWT Token
        refresh = RefreshToken.for_user(user)
        access_token = str(refresh.access_token)
        refresh_token = str(refresh)

        return Response({
            "detail": "登录成功。",
            "user": {
                "username": user.username,
                "email": user.email,
                "consecutive_login_days": profile.consecutive_login_days,
                "daily_check_in": profile.daily_check_in,
                "vocabulary_count": profile.vocabulary_count,
                "avatar": user.profile.avatar.url if user.profile.avatar else None,
                "is_avatar_approved": user.profile.is_avatar_approved,
            },
            "tokens": {
                "refresh": refresh_token,
                "access": access_token,
            }
        }, status=status.HTTP_200_OK)

class SendVerificationEmailView(generics.GenericAPIView):
    serializer_class = EmailVerificationSerializer
    permission_classes = [AllowAny]

    def post(self, request, *args, **kwargs):
        """
        发送邮箱验证码
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        email = serializer.validated_data['email']

        # 删除之前的验证码
        EmailVerification.objects.filter(email=email).delete()

        # 生成新的验证码
        code = generate_verification_code()
        verification = EmailVerification.objects.create(email=email, code=code)

        # 发送邮件
        subject = "SuperDe 注册验证码"
        from_email = settings.DEFAULT_FROM_EMAIL
        to = email
        context = {
            'username': email.split('@')[0],
            'code': code,
        }
        html_content = render_to_string('emails/verification_email.html', context)

        email_message = EmailMultiAlternatives(subject, '', from_email, [to])
        email_message.attach_alternative(html_content, "text/html")
        email_message.send()

        return Response({"detail": "验证码已发送到您的邮箱。"}, status=status.HTTP_200_OK)

class AvatarListView(generics.ListAPIView):
    queryset = Avatar.objects.all()
    serializer_class = AvatarSerializer
    permission_classes = [AllowAny]


class UserDailyActivityListView(generics.ListAPIView):
    """
    获取当前登录用户的所有每日活动数据
    """
    serializer_class = DailyActivitySerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        # 只返回当前登录用户的活动，并按日期排序
        return DailyActivity.objects.filter(user=self.request.user).order_by('date')

class CheckInView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        """
        用户点击“签到”
        """
        user = request.user
        profile = user.profile
        today = timezone.now().date()

        # 如果今天已经存在 DailyActivity 则不重复增加打卡次数
        daily_activity, created = DailyActivity.objects.get_or_create(user=user, date=today)
        if not daily_activity.is_logged_in:
            daily_activity.is_logged_in = True
            daily_activity.save()

            # 连续登录判断
            if profile.last_login_date == today - timezone.timedelta(days=1):
                profile.consecutive_login_days += 1
            elif profile.last_login_date != today:
                profile.consecutive_login_days = 1

            profile.last_login_date = today
            profile.daily_check_in += 1
            profile.save()

            return Response({"detail": "签到成功！"}, status=status.HTTP_200_OK)
        else:
            return Response({"detail": "今日已签到。"}, status=status.HTTP_400_BAD_REQUEST)